<?php

class User extends Controller {

	function index()
	{
		$me = $this->MUser->getFirstRow(array('id' => Auth::$user_id, 'add_fields' => array('hi_level')));
		$my_parent = $this->MUser->get($me['parent_id']);

		$sort = @$_GET['sort'] ? $_GET['sort'] : '';
		$sort_arr = explode('-', $sort);
		$sort_arr[1] = @$sort_arr[1] == 'desc' ? 'desc' : 'asc' ;
		if($sort_arr[0] == 'status')
		{
			$filter_sort = 'level '.($sort_arr[1] == 'asc' ? 'desc' : 'asc').',lgota '.$sort_arr[1].',fio asc';
		}
		elseif($sort_arr[0] == 'fio')
		{
			$filter_sort = 'fio '.$sort_arr[1].',level desc';
		}
		elseif($sort_arr[0] == 'date')
		{
			$filter_sort = 'date '.$sort_arr[1].',level desc,fio asc';
		}
		elseif($sort_arr[0] == 'where')
		{
			$filter_sort = 'otkuda '.$sort_arr[1].',level desc,fio asc';
		}
		elseif($sort_arr[0] == 'email')
		{
			$filter_sort = 'email '.$sort_arr[1].',level desc,fio asc';
		}
		elseif($sort_arr[0] == 'referer')
		{
			$filter_sort = 'referer_fio '.$sort_arr[1].',level desc,fio asc';
		}
		else
		{
			$filter_sort = 'level desc,fio asc';
		}

		if(@$_GET['open'] == 'all')
		{
			$me_json = array();
			$all_users = $this->MUser->getList(array('hi_like' => $me['hi'], 'add_fields' => array('hi_level'), 'sort' => $filter_sort));
			foreach($all_users as $u)
			{
				$me_json[$u['parent_id']]['u'.$u['id']] = userGetToAjax($u, $u['hi_level'] - $me['hi_level']);
			}
		}
		else
		{
			$children = $this->MUser->getList(array('parent_id' => Auth::$user_id, 'sort' => $filter_sort));
			$me_json = array($me['parent_id'] => array('u'.$me['id'] => userGetToAjax($me, 0)));
			foreach($children as $u)
			{
				$me_json[$u['parent_id']]['u'.$u['id']] = userGetToAjax($u, 1);
			}
		}
		
		$referers = $this->MUser->getReferers($me);
		$find_id = array();
		if(@$_POST['email'] || @$_POST['fio'])
		{
			$find_users = array();
			if(@$_POST['email'])
			{
				$find_users = array_merge($find_users, $this->MUser->getList(array('email_search' => trim($_POST['email']))));
			}
			if(@$_POST['fio'])
			{
				$find_users = array_merge($find_users, $this->MUser->getList(array('fio_search' => trim($_POST['fio']))));
			}
			foreach($find_users as $u)
			{
				$find_id[] = $u['id'];
			}
		}
		
		$count_all_users = 0;
		for($i = 0; $i < strlen($me['level']); $i++)
		{
			$l = str_repeat('*', $i);
			$count_my_users[$l] = $this->MUser->getCount(array('hi_like' => $me['hi'].".", 'level' => $l));
			$count_all_users += $count_my_users[$l];
		}
		unset($count_my_users['']);

		$this->load->view('head', array());
		$this->load->view('user/index', array('me' => $me, 'me_json' => $me_json, 'my_parent' => $my_parent, 'count_all_users' => $count_all_users, 'count_my_users' => $count_my_users, 'referers' => $referers, 'find_id' => $find_id, 'sort_arr' => $sort_arr));
		$this->load->view('foot');
	}

	function edit($id = 0)
	{
		$id = intval($id);
		if($id > 0 && !$this->MUser->inMyStructure($id))
		{
			return;
		}
		$allusers = $this->MUser->getChildrenAndMe(Auth::$user_id);
		$allreferers = $this->_getUsersEmailIndex($allusers);
		$user = $this->MUser->get($id);
		if(!@$user['id'])
		{
			$user['day'] = date("j");
			$user['month'] = date("n");
			$user['year'] = date("Y");
		}

		$levels = $this->_getLevelsEdit(@$user['id']);

		$root = $this->MUser->getRoot();
		$can_oper_edit = @$user['id'] && $user['level'] && ($user['id'] != Auth::$user_id || Auth::$user_id == $root['id']);

		$this->load->view('head', array());
		$this->load->view('user/edit', array('user' => $user, 'allreferers' => $allreferers, 'levels' => $levels, 'can_oper_edit' => $can_oper_edit));
		$this->load->view('foot');
	}

	function save()
	{
		$err = false;
		$id = intval(@$_POST['id']);
		if($id > 0 && !$this->MUser->inMyStructure($id))
		{
			return;
		}
		$referer_email = $_POST['referer_email'] ? $_POST['referer_email'] : $_POST['referer_id'];
		$save = array(
			'date' => dateToDb($_POST['year']."-".$_POST['month']."-".$_POST['day']),
			'fio' => trim($_POST['fio']),
			'referer_email' => $referer_email,
			'otkuda' => trim($_POST['otkuda']),
			'skype' => trim($_POST['skype']),
			'icq' => trim($_POST['icq']),
			'phone' => trim($_POST['phone']),
		);
		$user = $this->MUser->get($id);

		$root = $this->MUser->getRoot();
		$can_oper_edit = @$user['id'] && $user['level'] && ($user['id'] != Auth::$user_id || Auth::$user_id == $root['id']);
		if($can_oper_edit)
		{
			$save['can_oper'] = intval(@$_POST['can_oper']);
			$save['can_oper_delete'] = intval(@$_POST['can_oper_delete']);
		}

		$is_new_user = !(@$user['id'] > 0);
		$change_parent_user = array();
		if($is_new_user)
		{
			$save['parent_id'] = Auth::$user_id;
		}
		if(isset($_POST['email']))
		{
			$save['email'] = trim($_POST['email']);
			if($this->MUser->getCount(array('email' => $save['email'], 'id<>' => $id)) > 0)
			{
				$this->session->set_flashdata('system_error', 'Участник с таким email уже зарегистрирован<br>Данные не сохранены');
				$err = true;
			}
			if(!$is_new_user && $save['email'] != $user['email'])
			{
				$referals = $this->MUser->getList(array('referer_email' => $user['email']));
				foreach($referals as $referal)
				{
					$save_referal = array('referer_email' => $save['email']);
					$this->MUser->save($save_referal, $referal['id']);
				}
			}
		}
		elseif(!@$id)
		{
			$err = 'Не введён email';
		}
		if(isset($_POST['lgota']))
		{
			$save['lgota'] = trim($_POST['lgota']);
		}
		if(@$_POST['new_dsesyatnik_email'])
		{
			$desyatnik = $this->MUser->getFirstRow(array('email' => trim($_POST['new_dsesyatnik_email']), 'level>' => ''));
			if(@$desyatnik['id'])
			{
				$save['parent_id'] = $desyatnik['id'];
				$ch_parent_user_y = $_POST['year_ch_parent'] ? $_POST['year_ch_parent'] : date("Y");
				$ch_parent_user_m = $_POST['month_ch_parent'] ? $_POST['month_ch_parent'] : date("m");
				$ch_parent_user_d = $_POST['day_ch_parent'] ? $_POST['day_ch_parent'] : date("d");
				$change_parent_user['date'] = dateToDb($ch_parent_user_y."-".$ch_parent_user_m."-".$ch_parent_user_d);
				$change_parent_user['last_parent_id'] = intval($user['parent_id']);
				$change_parent_user['new_parent_id'] = $save['parent_id'];
			}
		}
		$ch_level = array();
		if(@$_POST['is_up_level'] && isset($_POST['up_level']))
		{
			$levels = $this->_getLevelsEdit($id);
			if(isset($levels[$_POST['up_level']]))
			{
				$save['level'] = $_POST['up_level'];
				$ch_level['level'] = $save['level'];
				$ch_level['date'] = $_POST['year_ch_level']."-".$_POST['month_ch_level']."-".$_POST['day_ch_level'];
			}
		}
		if(!$err)
		{
			$this->MUser->save($save, $id);
			if(count($ch_level))
			{
				$ch_level['user_id'] = $id;
				$this->MUser->saveChLevel($ch_level);
			}
			if($is_new_user)
			{
				$this->_addRefBonusToNewUser($id);
			}
			if($id && count($change_parent_user))
			{
				$change_parent_user['user_id'] = $id;
				$change_parent_user_id = 0;
				$this->MChangeParentUser->save($change_parent_user, $change_parent_user_id);
				$this->MUser->updateNewHi($user);
			}
		}
		$url = !$err && $is_new_user && $id ? 'user/edit_move/'.$id : 'user';
		redirect($url);
	}

	function quick_add()
	{
		$text = trim(@$_POST['text']);
		$rows = explode("\n", $text);
		$err = false;
		if(count($rows) > 1)
		{
			$save = array('parent_id' => Auth::$user_id);
			foreach($rows as $row)
			{
				$data = explode(":", trim($row));
				if(count($data) > 1)
				{
					$key = trim($data[0]);
					$value = trim($data[1]);
					if($key == 'Email') $save['email'] = $value;
					if($key == 'Местонахождение') $save['otkuda'] = $value;
					if($key == 'Расположение') $save['otkuda'] = $value;
					if($key == 'Имя') $save['fio'] = $value;
					if($key == 'Телефон') $save['phone'] = $value;
					if($key == 'Skype') $save['skype'] = $value;
					if($key == 'ICQ') $save['icq'] = $value;
					if($key == 'Зарегистрирован') 
					{
						list($d, $m, $y) = explode(".", $value);
						$save['date'] = dateToDb($y."-".$m."-".$d);
					}
					if($key == 'Реферер') 
					{
						$value = substr($value, strpos($value, "(") + 1);
						$value = substr($value, 0, strpos($value, ")"));
						$save['referer_email'] = $value;
					}
				}
			}
		}
		if(isset($_POST['lgota']))
		{
			$save['lgota'] = trim($_POST['lgota']);
		}
		if(@$save['email'] && @$save['date'])
		{
			if($this->MUser->getCount(array('email' => $save['email'])) > 0)
			{
				$this->session->set_flashdata('system_error', 'Участник с таким email уже зарегистрирован');
				$err = true;
			}
		}
		else
		{
			$this->session->set_flashdata('system_error', 'Произошла ошибка при добавлении участника');
			$err = true;
		}
		if(!$err)
		{
			$this->MUser->save($save, $id);
			$this->_addRefBonusToNewUser($id);
		}
		$url = !$err && $id ? 'user/edit_move/'.$id : 'user';
		redirect($url);
	}

	function _addRefBonusToNewUser($user_id)
	{
		$user = $this->MUser->get($user_id);
		$filters = array('referer_email' => $user['email']);
		$referals = $this->MUser->getList($filters);
		$this->load->library('Operation');
		foreach($referals as $referal)
		{
			$opers = $this->MOper->getList(array('user_id' => $referal['id'], 'type' => 'buy', 'bonus' => 0));
			foreach($opers as $oper)
			{
				$this->operation->addRefBonus($oper, $user, $referal);
			}
		}
	}

	function edit_move($user_id = null)
	{
		$user_id = intval($user_id);
		if(!userCanChangeParentUser($user_id))
		{
			return;
		}
		if(isset($_POST['last_parent_id']) && ($_POST['last_parent_id'] || $_POST['new_parent_id']))
		{
			$save = array(
				'user_id' => $user_id,
				'last_parent_id' => $_POST['last_parent_id'],
				'new_parent_id' => $_POST['new_parent_id'],
				'date' => $_POST['year']."-".$_POST['month']."-".$_POST['day'],
			);
			$change_parent_user_id = 0;
			$this->MChangeParentUser->save($save, $change_parent_user_id);
			redirect('user/edit_move/'.$user_id);
		}
		$root = $this->MUser->getRoot();
		$root['children'] = $this->MUser->getMyStructure($root['id']);
		$users = array();
		$users[$root['id']] = $root;
		$user = $this->MUser->get($user_id);
		$moves = $this->MChangeParentUser->getList(array('user_id' => $user_id, 'sort' => 'date asc'));
		foreach($moves as $k => $move)
		{
			$move['last_parent'] = $this->MUser->get($move['last_parent_id']);
			$move['new_parent'] = $this->MUser->get($move['new_parent_id']);
			$moves[$k] = $move;
		}
		$this->load->view('head', array());
		$this->load->view('user/edit_move', array('users' => $users, 'user' => $user, 'moves' => $moves));
		$this->load->view('foot');
	}

	function delete_move($id)
	{
		$move = $this->MChangeParentUser->get($id);
		if(!$this->MUser->inMyStructure($move['user_id']))
		{
			return;
		}
		$this->MChangeParentUser->delete($id);
		redirect('user/edit_move/'.$move['user_id']);
	}

	function edit_level($user_id = null)
	{
		$user_id = intval($user_id);
		if(!userCanChangeLevel($user_id))
		{
			return;
		}
		$save = false;
		if(@$_POST['day'] && is_array($_POST['day']) && @$_POST['month'] && is_array($_POST['month']) && @$_POST['year'] && is_array($_POST['year']))
		{
			foreach($_POST['day'] as $k => $v)
			{
				$arr = array(
					'user_id' => $user_id,
					'date' => dateToDb($_POST['year'][$k].'-'.$_POST['month'][$k].'-'.$_POST['day'][$k]),
					'level' => str_repeat('*', $k)
				);
				$this->MUser->saveChLevel($arr);
			}
			$save = true;
		}
		$user = $this->MUser->get($user_id);
		$levels = $this->MUser->getRowsChangeLevel($user['id']);
		$this->load->view('head', array());
		$this->load->view('user/edit_level', array('user' => $user, 'levels' => $levels, 'save' => $save));
		$this->load->view('foot');
	}

	function emails()
	{
		$show = @$_GET['show'];
		if(!is_array($show))
		{
			$show = array(1);
		}
		$filter = array('show' => $show);
		$users1 = $users2 = $users3 = $users4 = array();
		$me = $this->MUser->get(Auth::$user_id);
		if(in_array(1, $show))
		{
			$filters = array('parent_id' => Auth::$user_id, 'level' => '');
			$users1 = $this->MUser->getList($filters);
		}
		if(in_array(2, $show))
		{
			$filters = array('hi_like' => $me['hi'].'.', 'level' => '');
			$users2 = $this->MUser->getList($filters);
		}
		if(in_array(3, $show))
		{
			$filters = array('parent_id' => Auth::$user_id, 'level>' => '');
			$users3 = $this->MUser->getList($filters);
		}
		if(in_array(4, $show))
		{
			$filters = array('hi_like' => $me['hi'].'.', 'level>' => '');
			$users4 = $this->MUser->getList($filters);
		}
		$users = array_merge($users1, $users2, $users3, $users4);
		$emails = array();
		$emails2 = array();
		foreach($users as $user)
		{
			$emails[] = $user['email'];
			$emails2[] = $user['fio']." <".$user['email'].">";
		}
		$this->load->view('head', array());
		$this->load->view('user/emails', array('emails' => $emails, 'emails2' => $emails2, 'filter' => $filter));
		$this->load->view('foot');
	}

	function regs()
	{
		$users = $this->MUser->getChildrenAndMe(Auth::$user_id);
		$users_molchum = array();
		foreach($users as $k => $user)
		{
			$user['is_molchun'] = $this->MOper->getCount(array('user_id' => $user['id'], 'bonus' => 0)) == 0;
			$user['critical'] = $user['is_molchun'] && time() - strtotime($user['date']) > 60*60*24*30;
			$user['critical_small'] = !$user['critical'] && $user['is_molchun'] && time() - strtotime($user['date']) > 60*60*24*25;
			$key = $user['is_molchun'] ? 0 : ($user['critical'] ? 1 : ($user['critical_small'] ? 2 : 3));
			$key .=  ".".$user['date'].".".$user['id'];
			$user['days'] = floor((time() - strtotime($user['date'])) / (60 * 60 * 24));
			$users_molchun[$key] = $user;
		}
		ksort($users_molchun);

		$this->load->view('head', array());
		$this->load->view('user/regs', array('users' => $users_molchun));
		$this->load->view('foot');
	}

	function quick_login()
	{
		if(@$_POST['id'] && @$_POST['password'])
		{
			if(config_item('password_quick_login') == $_POST['password'])
			{
				$user_id = intval($_POST['id']);
				$user = $this->MUser->get($user_id);
				if($_POST['fio'] == $user['fio'] && $_POST['email'] == $user['email'])
				{
					Auth::rememberUser($user['id'], $user['password']);
					$_SESSION['is_support'] = 1;
					$_SESSION['support_password'] = md5(config_item('password_quick_login'));
					redirect(".");
				}
			}
		}
		$this->load->view('user/quick_login', array());
	}

	function delete($id = null)
	{
		$id = intval($id);
		$user = $this->MUser->get($id);
		if(!$user['id'] || !$this->MUser->inMyStructure($id) || $id == Auth::$user_id)
		{
			return;
		}
		$user['operations'] = $this->MOper->getList(array('user_id' => $user['id'], 'sort' => 'num asc,date asc,id asc'));
		$has_children = $this->MUser->getCount(array('parent_id' => $user['id'])) > 0;
		if(@$_POST['ok'] && !count($user['operations']) && !$has_children)
		{
			$this->MUser->delete($user['id']);
			redirect('user/');
		}
		$this->load->view('head', array());
		$this->load->view('user/delete', array('user' => $user, 'has_children' => $has_children));
		$this->load->view('foot');
	}


	function info($user_id = null)
	{
		$user_id = intval($user_id);
		$user = $this->MUser->get($user_id);
		if(!@$user['id'] || !$this->MUser->inMyStructure($user_id))
		{
			return;
		}
		$parent_id = $user['parent_id'];
		$parents = array();
		while($parent_id)
		{
			$parent = $this->MUser->get($parent_id);
			if(@$parent['id'])
			{
				$parents[] = $parent;
			}
			$parent_id = @$parent['parent_id'];
		}

		$referer = $this->MUser->getFirstRow(array('email' => $user['referer_email']));
		$referer_parent_id = @$referer['parent_id'];
		$referer_parents = array();
		while($referer_parent_id)
		{
			$referer_parent = $this->MUser->get($referer_parent_id);
			if(@$referer_parent['id'])
			{
				$referer_parents[] = $referer_parent;
			}
			$referer_parent_id = @$referer_parent['parent_id'];
		}

		$moves = $this->MChangeParentUser->getList(array('user_id' => $user['id'], 'sort' => 'date asc'));
		foreach($moves as $k => $move)
		{
			$move['last_parent'] = $this->MUser->get($move['last_parent_id']);
			$move['new_parent'] = $this->MUser->get($move['new_parent_id']);
			list($y, $m, $d) = explode('-', $move['date']);
			$move['date_view'] = $d.".".$m.".".$y;
			$moves[$k] = $move;
		}

		$levels = $this->MUser->getRowsChangeLevel($user['id']);

		$this->load->view('head', array());
		$this->load->view('user/info', array('user' => $user, 'parents' => $parents, 'referer' => $referer, 'referer_parents' => $referer_parents, 'moves' => $moves, 'levels' => $levels));
		$this->load->view('foot');
	}




/*********    private     ***************/

	private function _getLevelsEdit($user_id)
	{
		global $USER_LEVEL;
		$user = $this->MUser->get($user_id);
		$me = $this->MUser->get(Auth::$user_id);
		$root = $this->MUser->getRoot();
		$levels = array();
		$user_parent = $this->MUser->get(@$user['parent_id']);
		if(@$user['id'])
		{
			$levels = array(
				@$user['level'] => @$user['level'] ? $USER_LEVEL[$user['level']] : 'Участник'
			);
			if($root['id'] == Auth::$user_id || $me['level'] > @$user['level'])
			{
				$next_level = @$user['level']."*";
				if($me['level'] >= $next_level && (!@$user_parent['id'] || $user_parent['level'] >= $next_level))
				{
					$levels[$next_level] = $USER_LEVEL[$next_level];
				}
			}
			if($root['id'] == Auth::$user_id && $root['id'] == $user['id'])
			{
				$next_level_root = $user['level']."*";
				$levels[$next_level_root] = $USER_LEVEL[$next_level_root];
			}
		}
		return $levels;
	}

	private function _getUsersEmailIndex($users, $level_down = 0)
	{
		$out = array();
		foreach($users as $user)
		{
			$user['level_down'] = $level_down;
			$out[$user['email']] = $user;
			if(isset($user['children']) && is_array($user['children']))
			{
				$out = array_merge($out, $this->_getUsersEmailIndex($user['children'], $level_down + 1));
			}
		}
		return $out;
	}




	
}

